//index.js
let app = getApp();
var api = app.globalData.api
var util = app.globalData.utils

Page({
  data: {
    width: '',
    width2: '',
    width3: '',
    height2: '',
    height3: '',
    height4: '',
    paramsData: {},
    longitude: 106.93981627932543,
    latitude: 14.491727575010545,
    prelongitude: '',
    prelatitude: '',
    markers: [],
    choushui: 0,
    ishow: 0,
    rigger: {},
    content: 1,
    userid: '',
    uid: 0,
    pages: 0,
    scale: 4,
    markstate: 3,
    timeDate: "",
    adv: {},
    scaleParams: 0,
    mapHeight: '73vh',
    sumdata: {},
    isClick: 0,
    rankingList: [],
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '净滩地图', //导航栏 中间的标题
    },
    // 此页面 页面内容距最顶部的距离
    height: app.globalData.height * 2 + 20,
    account_id: 0,
    isOpen: true,
  },
  onOpen() {
    var that = this;
    that.setData({
      isOpen: !that.data.isOpen
    });
    if (that.data.isOpen == false) {
      that.setData({
        isLoading: 1,
        pages: 0,
        rankingList:[],
      })
      that.onRankingList();
    }
  },
  onSeach() {
    wx.navigateTo({
      url: '/pages/Activity/pages/activitySearch/index',
    })
  },
  showinfo() {
    wx.navigateTo({
      url: '/pages/Activity/pages/activityMapDetails/index',
    })
  },
  scalechange(e) {
    let that = this
    var state = e.currentTarget.dataset.state
    if (state == 1) {
      if (that.data.scale == 18) {
        that.setData({
          scale: 18
        })
      } else {
        that.getmapmarks(that.data.scale + 1)
        that.setData({
          scale: that.data.scale + 1
        })
      }
    } else if (state == 2) {
      if (that.data.scale == 5) {
        that.setData({
          scale: 5
        })
      } else {
        that.getmapmarks(that.data.scale - 1)
        that.setData({
          scale: that.data.scale - 1
        })
      }
    }
  },

  getmapmarks(scale) {
    let that = this
    this.mapCtx = wx.createMapContext("myMap");
    this.mapCtx.getCenterLocation({
      type: 'gcj02',
      success: function(latres) {
        that.setData({
          longitude: latres.longitude,
          latitude: latres.latitude
        })
      }
    })
    /**
     * 12 以上
     * scale 11 10 
     * 9 8 7 6
     * 5
     */
    if (scale >= 12 && that.data.scale < 12) {
      that.getmark(4)
      that.setData({
        scale: scale,
        markstate: 4
      })
    }
    if (scale >= 10 && scale <= 11 && (that.data.scale > 11 || that.data.scale < 10)) {
      that.setData({
        scale: scale,
        markstate: 3
      })
    }
    if (scale >= 7 && scale <= 9 && (that.data.scale > 9 || that.data.scale < 7)) {
      that.setData({
        scale: scale,
        markstate: 2
      })
    }
    if (scale <= 6 && (that.data.scale > 6)) {
      that.getmark(1)
      that.setData({
        scale: scale,
        markstate: 1
      })
    }
  },
  getmark(scale) {
    let that = this;
    wx.showLoading({
      title: '正在加载中',
    })
    let data = {
      longitude: that.data.longitude,
      latitude: that.data.latitude,
      scale: scale,
    }
    let url = app.u.H + app.u.river.ACTIVITYMAP
    // let url = "http://river.cc/api/index/scaleindex"
    api.requestUrl(data, url).then(res => {
      setTimeout(function() {
        wx.hideLoading()
      }, 500)
      if (res.code == 200) {
        let actList = res.data[0].actList
        if (actList.length > 0) {
          that.setData({
            markers: actList,
            sumdata: res.data[0],
            scaleParams: scale,
          })
        } else {
          wx.showToast({
            title: '暂无数据',
            icon: 'success',
            duration: 2000
          })
        }
      }
    })
  },
  regionchange(e) {
    var that = this;
    // 地图发生变化的时候，获取中间点，也就是用户选择的位置toFixed
    if (e.type == 'end' && (e.causedBy == 'scale')) {
      that.mapCtx = wx.createMapContext("map");
      that.mapCtx.getScale({
        type: 'gcj02',
        success: function(res) {
          that.mapCtx.getCenterLocation({
            type: 'gcj02',
            success: function(latres) {
              that.setData({
                latitude: latres.latitude,
                longitude: latres.longitude
              })
              if (res.scale <= 4) {
                if (that.data.scaleParams !== 1) {
                  if (that.data.paramsData.province !== undefined) {
                    delete that.data.paramsData.province
                  }
                  that.getmark(1)
                }
              } else if (res.scale >= 7 && that.data.isClick !== 1) {
                if (that.data.scaleParams !== 4) {
                  var dis = that.getDistance(latres.latitude, latres.longitude, that.data.prelatitude, that.data.prelongitude)
                  if (dis > 3000) {
                    that.setData({
                      prelatitude: latres.latitude,
                      prelongitude: latres.longitude
                    })
                    that.getmark(4)
                  }
                }
              }
            }
          })
        }
      })
    }
  },
  onLocation(e) {
    let that = this
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/Activity/pages/activityInfo/index?id=' + e.currentTarget.dataset.id,
    })
  },

  onItem(markerId) {
    let that = this;
    let markers = that.data.markers;
    let markersItem = ""
    let index = -1
    for (var i in markers) {
      if (markers[i].id == markerId) {
        markersItem = markers[i]
        index = i
      }
    }
    let obj = {
      markersItem: markersItem,
      index: index,
    }
    return obj;
  },
  close: function() {
    this.setData({
      content: 1
    })
  },
  activityInfo(e) {
    wx.navigateTo({
      url: '/pages/Activity/pages/activityInfo/index?id=' + e.currentTarget.dataset.markid,
    })
  },
  bindcallouttap(e) {
    let that = this;
    let markerId = e.markerId;
    let markersObj = that.onItem(markerId);
    let markersItem = markersObj.markersItem;
    let index = markersObj.index;
    that.setData({
      isClick: 1,
    })
    if (that.data.paramsData.province != undefined || that.data.scaleParams == 4) {
      wx.navigateTo({
        url: '/pages/Activity/pages/activityInfo/index?id=' + markerId,
      })
      that.data.markers[index].iconPath = "/pages/res/quan.png"
      that.data.markers[index].width = 50
      that.data.markers[index].height = 50
      that.data.markers[index].label = {
        anchorX: -30,
        anchorY: -5,
        bgColor: "#FFFFFF",
        borderColor: "#ffffff",
        borderRadius: 40,
        color: "#101010",
        content: markersItem.address ? markersItem.address : (markersItem.district ? markersItem.district : ''),
        fontSize: 12,
        padding: 6,
      }
      that.setData({
        markers: that.data.markers
      })
    } else {
      let data = {
        long: markersItem.longitude,
        lat: markersItem.latitude,
        province: markersItem.province,
        scale: 4
      }
      that.setData({
        scale: 7,
        longitude: markersItem.longitude,
        latitude: markersItem.latitude,
      })
      that.onMarkers(data);
    }
  },
  onMarkers(params) {
    let that = this;
    wx.showLoading({
      title: '正在加载中',
    })
    var url = app.u.H + app.u.river.ACTIVITYMAP
    api.requestUrl(params, url).then(res => {
      setTimeout(function() {
        wx.hideLoading()
      }, 500)
      if (res.code == 200) {
        let array = res.data[0].actList
        if (array.length > 0) {
          if (params.scale == 1) {
            that.setData({
              longitude: 106.93981627932543,
              latitude: 14.491727575010545,
            })
          } else {
            that.setData({
              latitude: res.data[0].location.lat,
              longitude: res.data[0].location.lng,
            })
          }
          that.setData({
            markers: res.data[0].actList,
            sumdata: res.data[0],
            scaleParams: params.scale,
            paramsData: params,
            isClick: 0
          })
        } else {
          wx.showToast({
            title: '暂无数据',
            icon: 'success',
            duration: 2000
          })
        }
      }
    })
  },
  village_LBS() {
    var that = this;
    // ------------ 腾讯LBS地图  --------------------
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function(res) {
        // 调用接口, 坐标转具体位置 -xxz0717
        // that.setData({
        //   longitude: res.longitude,
        //   latitude: res.latitude,
        // })
        var data = {
          long: res.longitude,
          lat: res.latitude,
          scale: 1
        }
        that.onMarkers(data);
      }
    })
  },
  getDistance: function(lat1, lng1, lat2, lng2) {
    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;

    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var r = 6378137;
    var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));
    return distance;
  },
  onLoad: function(options) {
    let that = this;
    let data2 = {}
    var url2 = app.u.H + app.u.river.ADV
    api.requestUrl(data2, url2).then(res => {
      if (res.code == 200) {
        that.setData({
          adv: res.data
        })
      }
    })
    wx.getStorage({
      key: 'userinfo',
      success: function(res) {
        that.setData({
          userid: res.data.id
        })
      },
    })
    var data = {
      long: that.data.latitude,
      lat: that.data.latitude,
      scale: 1
    }
    that.setData({
      scale: 3
    })
    that.onMarkers(data)
  },
  onShouQuan(e) {
    let that = this;
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) { //非初始化进入该页面,且未授权
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
            success: function(res) {
              if (res.cancel) {} else if (res.confirm) {
                wx.openSetting({
                  success: function(data) {
                    if (data.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用getLocationt的API
                      that.village_LBS();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) { //初始化进入
          that.village_LBS();
        }
      }
    })
  },
  onShow: function() {
    var that = this
    wx.getLocation({
      type: 'gcj02',
      success: function(res) {},
      fail: function(e) {
        that.onShouQuan(e);
      }
    })
    that.setData({
      timeDate: util.formatTime(new Date()),
    })
  },
  onRankingList() {
    var that = this
    let data = {
      pages: that.data.pages + 1,
    }
    that.setData({
      isLoading: 0,
    })
    var url = app.u.H + app.u.river.FINDACTIVITY
    api.requestUrl(data, url).then(res => {
      if (res.code == 200) {
        let data = res.data
        console.log(data.count, data.pages)
        let isShow = data.count > data.pages ? 1 : -1
        console.log(data.pages + 1)
        that.setData({
          rankingList: that.data.rankingList.concat(res.data.list),
          pages: data.pages,
          isLoading: isShow,
        })
      } else {
        api.showError(res.msg);
      };
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onReachBottom: function() {
    // var that = this
    // let data = {
    //   pages: that.data.pages + 1,
    // }
    // var url = app.u.H + app.u.river.FINDACTIVITY
    // api.requestUrl(data, url).then(res => {
    //   if (res.code == 200) {
    //     that.setData({
    //       rankingList: that.data.rankingList.concat(res.data),
    //       pages: that.data.pages + 1
    //     })
    //   } else {
    //     api.showError(res.msg);
    //   };
    // });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},
  onShareAppMessage: function(res) {
    var that = this
    api.ageshare()
    that.setData({
      uid: wx.getStorageSync('userinfo').id
    })
    return {
      title: "净滩地图",
      path: "pages/Activity/pages/activityMap/index?account_id=" + that.data.uid
    }
  },
})